package dcc.component;

import java.awt.Font;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.List;

import javax.swing.JTable;

import org.jdesktop.beansbinding.AutoBinding.UpdateStrategy;
import org.jdesktop.beansbinding.BeanProperty;
import org.jdesktop.swingbinding.JTableBinding;
import org.jdesktop.swingbinding.SwingBindings;

import dcc.mbg.model.Dictionary;
import dcc.mbg.model.DictionaryItem;
import dcc.tools.BeanFactory;

public class JDictionaryItemTable extends JTable {

	private JDictionaryPanel dictionaryPanel;

	public JDictionaryItemTable(JDictionaryPanel dictionaryPanel) {
		this.dictionaryPanel = dictionaryPanel;
		setFont(new Font("Microsoft YaHei", Font.PLAIN, 18));
		this.setRowHeight(30);
		this.getTableHeader().setFont(new Font("Microsoft YaHei", Font.PLAIN, 18));
		this.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				if (1 == e.getClickCount()) {
					getSelectedValue();
				}
			}
		});
	}

	private void getSelectedValue() {
		int rowIndex = this.getSelectedRow();
		if (-1 == rowIndex) {
			return;
		} else {
			dictionaryPanel.setValue(getItem(this.getModel()
					.getValueAt(rowIndex, 0).toString()));
		}
	}

	private DictionaryItem getItem(String value) {
//		for (DictionaryItem item : this.dictionary.getValues()) {
//			if (item.getValue().equals(value)) {
//				return item;
//			}
//		}
		return null;
	}

	private Dictionary dictionary;

	public void update(Dictionary dictionary) {
//		if (dictionary != null) {
//			this.dictionary = dictionary;
//			initDataBindings(this.dictionary.getValues());
//		}
	}

	public void update(int id) {
//		((DictionaryService) BeanFactory.getBean("dictionaryService"))
//				.removeItem(id);
		dictionaryList.updateTable();
	}

	protected void initDataBindings(List<DictionaryItem> values) {
		JTableBinding<DictionaryItem, List<DictionaryItem>, JTable> jTableBinding = SwingBindings
				.createJTableBinding(UpdateStrategy.READ, values, this);
		//
		BeanProperty<DictionaryItem, String> dictionaryItemBeanProperty = BeanProperty
				.create("value");
		jTableBinding.addColumnBinding(dictionaryItemBeanProperty)
				.setColumnName("\u503C").setEditable(false);

		//
		BeanProperty<DictionaryItem, String> deleteButtonBeanProperty = BeanProperty
				.create("id");
		jTableBinding.addColumnBinding(deleteButtonBeanProperty).setColumnName(
				"\u64CD\u4F5C");
		//
		jTableBinding.bind();

		this.getColumnModel().getColumn(1).setMaxWidth(40);
		getColumnModel().getColumn(1).setCellRenderer(
				new DeleteButtonRenderer());
		getColumnModel().getColumn(1).setCellEditor(
				new DictionaryItemDeleteButtonEditor(this));
	}

	public void setDictionaryList(JDictionaryList dictionaryList) {
		this.dictionaryList = dictionaryList;
	}
	
	private JDictionaryList dictionaryList;
}
